//
//  TstZfChooseSessionVC.swift
//  Tinsecret_TW
//
//  Created by wanghui on 2018/10/30.
//  Copyright © 2018年 tst. All rights reserved.
//  (转发)选择一个聊天

import UIKit

class TstZfChooseSessionVC: ChatBaseController {
    var msg:ChatMessage?
    var superServerID:Int = 0 //super 会话窗口的serverid
    
    lazy var tableView:UITableView = {
        let tableView = UITableView(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height), style: .plain)
        tableView.tableFooterView = UIView.init(frame: CGRect.zero)
        tableView.dataSource = (self as UITableViewDataSource)
        tableView.delegate = (self as UITableViewDelegate)
        
        tableView.register(UINib.init(nibName: "createNewSessionHeadView", bundle: nil), forHeaderFooterViewReuseIdentifier: "createNewSessionHeadView")
        tableView.register(tstPtPcell.self, forCellReuseIdentifier: "tstPtPcell")
        tableView.register(groupcell.self, forCellReuseIdentifier: "groupcell")
        tableView.register(chooseSesForTwo.self, forCellReuseIdentifier: "chooseSesForTwo")
        tableView.register(UINib(nibName: "chooseSesForTwo",bundle: nil), forCellReuseIdentifier: "chooseSesForTwo")
        tableView.register(UINib(nibName: "chooseSesForThree",bundle: nil), forCellReuseIdentifier: "chooseSesForThree")
        tableView.register(UINib(nibName: "chooseSeForFour",bundle: nil), forCellReuseIdentifier: "chooseSeForFour")
        tableView.register(UINib(nibName: "chooseSeForFive",bundle: nil), forCellReuseIdentifier: "chooseSeForFive")
        tableView.register(UINib(nibName: "chooseSeForSix",bundle: nil), forCellReuseIdentifier: "chooseSeForSix")
        tableView.register(UINib(nibName: "chooseSeForSeven",bundle: nil), forCellReuseIdentifier: "chooseSeForSeven")
        tableView.register(UINib(nibName: "chooseSeForEight",bundle: nil), forCellReuseIdentifier: "chooseSeForEight")
        tableView.register(UINib(nibName: "chooseSeForNine",bundle: nil), forCellReuseIdentifier: "chooseSeForNine")
       
        
        tableView.rowHeight = 70
        return tableView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        notificationObserve()
        setUI()
    }
    
    let service = SessionService()
    var sessionList = [ChatSession]()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension TstZfChooseSessionVC {
    func loadData() {
        DispatchQueue.global().async {
            self.sessionList = self.service.getAllRecentSessions()
            if self.sessionList.count > 0 {
                var unreadcount:Int = 0
                for session in self.sessionList{
                    if !session.noDisturbing {
                        unreadcount += session.unreadCount
                    }
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                    if unreadcount > 0 {
                        self.tabBarItem.pp.addBadge(text: "\(unreadcount > 99 ? "99+" : "\(unreadcount)")")
                    }else {
                        self.tabBarItem.pp.hiddenBadge()
                    }
                }
            }
        }
    }
    
    func setUI() {
        self.view.addSubview(tableView)
        let homepageview = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(buttonTap))
        self.navigationItem.leftBarButtonItems = [homepageview]
        
        let headview = Bundle.main.loadNibNamed("createNewSessionHeadView", owner: nil, options: nil)?.last as! UIView
        self.tableView.tableHeaderView = headview
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapHeaderEvent))
        headview.addGestureRecognizer(tap)
        
    }
    
    @objc func buttonTap() {
        DispatchQueue.main.async {
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    @objc func tapHeaderEvent() {
        let addbookVC = TstAddressbookVC()
        addbookVC.title = NSLocalizedString("选择联系人",comment:"选择联系人")
        addbookVC.msg = self.msg
        self.navigationController?.pushViewController(addbookVC, animated: true)
    }
    
    func notificationObserve() {
        // 添加通知监听
        NotificationCenter.default.addObserver(self, selector: #selector(getnewMsg(notification:)), name: Notification.Name("onNewMsg"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(onStatusChange), name: connectionStatusChange, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(buttonTap), name: closeCurrentVCNoti, object: nil)
    }
    
    @objc func getnewMsg(notification: Notification) {
        loadData()
    }
    
    @objc func rightbuttonTap(button:UIButton) {
        let vc = TstChooseContactVC();
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func onStatusChange(note: Notification) {
        guard let data = note.userInfo,let newStatus = data["newStatus"] as? Int,let status = ConnectionStatus(rawValue:newStatus) else {
            return
        }
        DispatchQueue.main.async {
            switch status {
            case .Connecting :
                self.navigationItem.title = NSLocalizedString("聊天(连接中)",comment:"聊天(连接中)")
            case .Login :
                self.navigationItem.title = NSLocalizedString("聊天(连接中)",comment:"聊天(连接中)")
            case .ConnectOK:
                self.navigationItem.title = NSLocalizedString("聊天",comment:"聊天")
            case .LoginOK:
                self.navigationItem.title = NSLocalizedString("聊天",comment:"聊天")
            default:
                self.navigationItem.title = NSLocalizedString("聊天(未连接)",comment:"聊天(未连接)")
            }
        }
    }
}

extension TstZfChooseSessionVC: UITableViewDataSource, UITableViewDelegate{
    
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let session = sessionList[indexPath.row]
        if session.session.chatType == .p2p {
            let tstPtPcell = "tstPtPcell"
            let cell = tableView.dequeueReusableCell(withIdentifier: tstPtPcell, for: indexPath) as! tstPtPcell
            cell.nameLabel.text = session.sessionName
            cell.headimage.kf.setImage(with: Common.avatarUrl(session.avatar ?? "") ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
            return cell
            
        } else {
            let group = self.sessionList[indexPath.row]
            let memberCount = group.avatars.count
            switch memberCount {
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: "groupcell", for: indexPath) as! groupcell
                let group = self.sessionList[indexPath.row]
                cell.nameLabel.text = group.sessionName
                cell.headimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                return cell
            case 2 :
                let cell = tableView.dequeueReusableCell(withIdentifier: "chooseSesForTwo", for: indexPath) as! chooseSesForTwo
                let group = self.sessionList[indexPath.row]
                cell.namelabel.text = group.sessionName
             
                cell.firstimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.secondimg.kf.setImage(with: Common.avatarUrl(group.avatars[1] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                
                return cell
            case 3 :
                let cell = tableView.dequeueReusableCell(withIdentifier: "chooseSesForThree", for: indexPath) as! chooseSesForThree
                let group = self.sessionList[indexPath.row]
                cell.namelabel.text = group.sessionName
                cell.firstimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.secondimg.kf.setImage(with: Common.avatarUrl(group.avatars[1] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.thirdimg.kf.setImage(with: Common.avatarUrl(group.avatars[2] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                return cell
            case 4 :
                let cell = tableView.dequeueReusableCell(withIdentifier: "chooseSeForFour", for: indexPath) as! chooseSeForFour
                let group = self.sessionList[indexPath.row]
                cell.namelabel.text = group.sessionName
                cell.firstimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.secondimg.kf.setImage(with: Common.avatarUrl(group.avatars[1] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.thirdimg.kf.setImage(with: Common.avatarUrl(group.avatars[2] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fourthimg.kf.setImage(with: Common.avatarUrl(group.avatars[3] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                return cell
            case 5 :
                let cell = tableView.dequeueReusableCell(withIdentifier: "chooseSeForFive", for: indexPath) as! chooseSeForFive
                let group = self.sessionList[indexPath.row]
                cell.namelabel.text = group.sessionName
                cell.firstimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.secondimg.kf.setImage(with: Common.avatarUrl(group.avatars[1] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.thirdimg.kf.setImage(with: Common.avatarUrl(group.avatars[2] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fourthimg.kf.setImage(with: Common.avatarUrl(group.avatars[3] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fifthimg.kf.setImage(with: Common.avatarUrl(group.avatars[4] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                return cell
            case 6 :
                let cell = tableView.dequeueReusableCell(withIdentifier: "chooseSeForSix", for: indexPath) as! chooseSeForSix
                let group = self.sessionList[indexPath.row]
                cell.namelabel.text = group.sessionName
          
                cell.firstimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.secondimg.kf.setImage(with: Common.avatarUrl(group.avatars[1] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.thirdimg.kf.setImage(with: Common.avatarUrl(group.avatars[2] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fourthimg.kf.setImage(with: Common.avatarUrl(group.avatars[3] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fifthimg.kf.setImage(with: Common.avatarUrl(group.avatars[4] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.sixthimg.kf.setImage(with: Common.avatarUrl(group.avatars[5] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                return cell
            case 7 :
                let cell = tableView.dequeueReusableCell(withIdentifier: "chooseSeForSeven", for: indexPath) as! chooseSeForSeven
                let group = self.sessionList[indexPath.row]
                cell.namelabel.text = group.sessionName
                
                cell.firstimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.secondimg.kf.setImage(with: Common.avatarUrl(group.avatars[1] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.thirdimg.kf.setImage(with: Common.avatarUrl(group.avatars[2] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fourthimg.kf.setImage(with: Common.avatarUrl(group.avatars[3] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fifthimg.kf.setImage(with: Common.avatarUrl(group.avatars[4] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.sixthimg.kf.setImage(with: Common.avatarUrl(group.avatars[5] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.sevenimg.kf.setImage(with: Common.avatarUrl(group.avatars[6] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
    
                return cell
            case 8 :
                let cell = tableView.dequeueReusableCell(withIdentifier: "chooseSeForEight", for: indexPath) as! chooseSeForEight
                let group = self.sessionList[indexPath.row]
                cell.namelabel.text = group.sessionName
                cell.firstimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.secondimg.kf.setImage(with: Common.avatarUrl(group.avatars[1] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.thirdimg.kf.setImage(with: Common.avatarUrl(group.avatars[2] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fourthimg.kf.setImage(with: Common.avatarUrl(group.avatars[3] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fifthimg.kf.setImage(with: Common.avatarUrl(group.avatars[4] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.sixthimg.kf.setImage(with: Common.avatarUrl(group.avatars[5] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.sevenimg.kf.setImage(with: Common.avatarUrl(group.avatars[6] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.eighthimg.kf.setImage(with: Common.avatarUrl(group.avatars[7] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                return cell
            case 9 :
                let cell = tableView.dequeueReusableCell(withIdentifier: "chooseSeForNine", for: indexPath) as! chooseSeForNine
                let group = self.sessionList[indexPath.row]
                cell.namelabel.text = group.sessionName
                cell.firstimage.kf.setImage(with: Common.avatarUrl(group.avatars[0] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.secondimg.kf.setImage(with: Common.avatarUrl(group.avatars[1] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.thirdimg.kf.setImage(with: Common.avatarUrl(group.avatars[2] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fourthimg.kf.setImage(with: Common.avatarUrl(group.avatars[3] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.fifthimg.kf.setImage(with: Common.avatarUrl(group.avatars[4] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.sixthimg.kf.setImage(with: Common.avatarUrl(group.avatars[5] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.sevenimg.kf.setImage(with: Common.avatarUrl(group.avatars[6] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.eighthimg.kf.setImage(with: Common.avatarUrl(group.avatars[7] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                cell.nineimg.kf.setImage(with: Common.avatarUrl(group.avatars[8] ) ?? URL(string: "localhost")!, placeholder: UIImage.init(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: "groupcell", for: indexPath) as! groupcell
                let group = self.sessionList[indexPath.row]
                print("群聊名称：\(group.sessionName)，lastMsg:\(group.lastMsg?.msgText)")
                cell.nameLabel.text = group.sessionName
                cell.headimage.image = UIImage.init(named: "timg")
               
                return cell
            }
        }
    }
    
    // delegate
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sessionList.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         let sendVC = sendToVC()
        tableView.deselectRow(at: indexPath, animated: true)
        
        let session = sessionList[indexPath.row]
        sendVC.msg = msg
        if session.session.chatType == .p2p {
            sendVC.type = 0
            sendVC.group = session
            sendVC.specialAvatar = session.avatar
        }else {
            sendVC.type = 1
            let memberCount = session.avatars.count
            sendVC.group = session
            sendVC.memberCount = memberCount
        }
        sendVC.sessionServerId =  session.session.sessionServerId
        
        sendVC.definesPresentationContext = true;
        sendVC.modalPresentationStyle = .overFullScreen
        sendVC.modalTransitionStyle = .crossDissolve
        self.present(sendVC, animated: true)
    }
}
